<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">

        <el-alert title="首先输入账号信息查询，若不存在则自动创建" type="info" />
        <br>
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px"
				 label-position="left">
			<el-form-item label="手机号/账号" prop="mobile">
				<el-input v-model="form.mobile" maxlength="11" placeholder="请输入手机号" clearable style="width: 50%;"></el-input>
                <view class="user-item">
                    <el-image class="u-avatar" :src="userInfo.avatar" fit="fill" />
                    <p class="p1" v-text="userInfo.realname"></p>
                    <p class="p2" v-text="userInfo.register_time?userInfo.register_time:'点击下一步自动注册'"></p>
                </view>
			</el-form-item>
            <el-form-item label="部门" prop="dept_id">
                <el-cascader filterable v-model="form.dept_id" :options="deptOptions" :props="deptProps" :show-all-levels="false"
                             style="width: 100%" placeholder="请选择部门" clearable></el-cascader>
            </el-form-item>
			<el-form-item label="职位" prop="position_id">
				<el-select filterable v-model="form.position_id" placeholder="请选择职位" style="width: 100%">
					<el-option v-for="item in positionList" :label="item.name" :value="item.id" :key="item.id" />
				</el-select>
			</el-form-item>
            <el-form-item label="入职时间" prop="in_time">
                <el-date-picker v-model="form.in_time" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" style="width: 100%;"></el-date-picker>
<!--                <el-input v-model="form.in_time" maxlength="11" placeholder="请选择入职时间" clearable></el-input>-->
            </el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()" title="点击继续完善资料">下一步</el-button>
		</template>
	</el-dialog>
</template>

<script>
import {verifyPhone} from "@/utils/verificate";
export default {
	emits: ['next', 'closed', 'reloadData'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增员工',
			},
			visible: false,
			isSaveing: false,
			// 职位select数据
			positionList:[],
            // 部门树数据
            deptOptions: [],
            deptProps: {
                value: 'id',
                label: 'name',
                checkStrictly: true
            },
			//表单数据
			form: {
				mobile: '',//账号
				position_id: '',//职位ID
                dept_id: '',
                in_time: this.$TOOL.dateFormat(new Date())
			},
			// 修改密码
			changePassword: '',
			//验证规则
			rules: {
				mobile: [
					{required: true, message: '请输入手机号'},
					{validator: verifyPhone, trigger: 'blur'}
				],
                dept_id: [
					{required: true, message: '请选择部门'}
				],
                position_id: [
                    {required: true, message: '请选择职位'}
                ],
                in_time: [
                    {required: true, message: '请选择入职日期'}
                ]
			},
            userInfo: {
                realname: '未注册',
                avatar: '/admin/img/avatar.png',
                register_time: ''
            },
            queryUser: {
                last: '',
                last_time: new Date().getTime()
            }
		}
	},
    watch: {
        'form.mobile': function () {
            const time = new Date().getTime();
            //手机号输入 -查询数据库
            if(this.queryUser.last_time > time - 500){
                return;
            }
            this.queryUser.last_time = time;

            this.userInfo.realname = '查询中...';
            setTimeout(() =>{
                this.onQueryUser();
            }, 500)
        }
    },
	methods: {
        onQueryUser() {
            this.$API.company.employee.add.post({
                query_user: this.form.mobile
            }).then((res) => {
                if(res.data){
                    if(!res.data.avatar) res.data.avatar = '/admin/img/avatar.png';
                    res.data.register_time = this.$TOOL.dateFormat(res.data.register_time * 1000)
                    this.userInfo = res.data
                }else{
                    this.userInfo = {
                        realname: '未注册',
                        avatar: '/admin/img/avatar.png',
                        register_time: ''
                    }
                }
                console.log(res)
            })
        },
        //简单化菜单
        treeToMap(tree) {
            let map = [];
            tree.forEach(item => {
                const obj = {
                    id: item.id,
                    parentId: item.pid,
                    name: item.name,
                    children: item.children && item.children.length > 0 ? this.treeToMap(item.children) : null
                }
                map.push(obj)
            })
            return map
        },
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			// 请求岗位列表的数据
			this.$API.company.employee.edit.get().then((res) => {
				this.positionList= res.data.positions.rows
                this.deptOptions = this.treeToMap(res.data.depts)
			})
			return this
		},
		//表单提交方法
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					let res = await this.$API.company.employee.add.post(this.form);
					this.isSaveing = false;
					if (res.code === 0) {
                        this.$emit('reloadData')
                        this.$emit('next')
						this.visible = false;
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", {type: 'error'})
					}
				} else {
					return false;
				}
			})
		}
	}
}
</script>

<style scoped lang="scss">
.user-item{
    position: relative;
    width: 50%;
    .u-avatar{
        position: absolute;
        left: 5px;
        top: -15px;
        width: 30px;
        height: 30px;
    }
    p{
        position: absolute;
        left: 45px;
    }
    .p1{
        top: -23px;
        width: 9em;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .p2{
        font-size: 11px;
        color: #999;
        top: -6px;
    }

}

</style>
